package com.mrjy.video.bo;

import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.UserVideoRel;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.ResponseCode;
import com.mrjy.custom.dto.CustomModuleCoursePackageDto;
import com.mrjy.integral.dao.IIntegralInfoDao;
import com.mrjy.video.dao.IUserVideoRelDao;
import com.mrjy.video.dao.IVideoInfoDao;
import com.mrjy.video.dto.CoursePackageViewDTO;
import com.mrjy.video.dto.SignInKeepDayDTO;
import com.mrjy.video.dto.StundentRankingDTO;
import com.mrjy.video.dto.VideoViewDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("UserVideoRelBo")
public class UserVideoRelBo implements IUserVideoRelBo {
	@Resource
	private IUserVideoRelDao userVideoRelDao;
	@Resource
	private IVideoInfoDao videoInfoDao;
    @Resource
    private IIntegralInfoDao integralInfoDao;

    @Override
	public Object txInsert(UserVideoRel rel) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == rel){
			map.put("err_code", -1);
			map.put("err_msg", "传进来的对象为空");
			return map;
		}
		rel.setCreateTime(new Date());
		int count = userVideoRelDao.insert(rel);
		if (count > 0) {
			map.put("err_code", 0);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "插入失败");
		}
		return map;	
	}

	@Override
	public Object txUpdateById(UserVideoRel rel) {
		return userVideoRelDao.updateById(rel);
	}

	@Override
	public Object queryByUserIdAndVideoId(UserVideoRel rel) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == rel){
			map.put("err_code", ResponseCode.USER_ERROR.getCode());
			map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
			return map;
		}
		
		if(rel.getUserId().equals(0)){
			map.put("err_code", ResponseCode.VISITOR_STATUS.getCode());
			map.put("err_msg", ResponseCode.VISITOR_STATUS.getDesc());
			return map;
		}
		
		int count = userVideoRelDao.queryByUserIdAndVideoId(rel);
		int row = 0;
		if(count > 0){//有观看记录,则update
            rel.setLastViewTime(new Timestamp(System.currentTimeMillis()));
            row = userVideoRelDao.updateByUserIdAndVideoId(rel);
			if (row>0) {
				map.put("err_code", 1);
				map.put("err_msg", "更新观看记录成功");
			}else {
				map.put("err_code", -1);
				map.put("err_msg", "更新观看记录失败");
			}
			return map;
		}else {//如果没有观看过，则直接新增
			if(rel.getUserId() != null && rel.getVideoId() != null){
				rel.setCreateTime(new Date());
				rel.setLastViewTime(new Timestamp(rel.getCreateTime().getTime()));
				try {
					row = userVideoRelDao.insert(rel);
				} catch (Exception e) {
					//捕获数据库插入重复数据报的错
					e.printStackTrace();
					rel.setLastViewTime(new Timestamp(System.currentTimeMillis()));
					row = userVideoRelDao.updateByUserIdAndVideoId(rel);
					if (row>0) {
						map.put("err_code", 1);
						map.put("err_msg", "更新观看记录成功");
					}else {
						map.put("err_code", -1);
						map.put("err_msg", "更新观看记录失败");
					}
					return map;
				}
				if(row == 1){
					map.put("err_code", 0);
					map.put("err_msg", "插入观看记录成功");
				}else{
					map.put("err_code", 2);
					map.put("err_msg", "插入观看记录失败");
				}
			}else {
				map.put("err_code", 3);
				map.put("err_msg", "用户id或者视频id为null");
			}
		}
		return map;
	}

	@Override
	public Object queryViewProgress(UserVideoRel rel) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null == rel.getUserId() || null == rel.getVideoId()) {
			map.put("err_code", 400);
			map.put("err_msg", "参数异常");
			return map;
		}
		UserVideoRel userVideoRel = userVideoRelDao.queryInfoByUserIdAndVideoId(rel);
		if (userVideoRel!=null) {
			map.put("err_code", 0);
			map.put("err_msg", "用户观看过此视频");
			map.put("rows", userVideoRel);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "无观看记录");
		}
		return map;
	}

	@Override
	public Object updateByUserIdAndVideoId(UserVideoRel rel) {
		Map<String, Object> map = new HashMap<String, Object>();
        if (null == rel.getUserId() || null == rel.getVideoId() || (StringUtils.isBlank(rel.getLastViewDuration()) &&
                StringUtils.isBlank(rel.getLastViewDurationAudio())) || StringUtils.isBlank(rel.getMessageString())) {
            map.put("err_code", 400);
            map.put("err_msg", "参数异常");
			return map;
		}
		if(rel.getUserId().equals(0)){
			map.put("err_code", ResponseCode.VISITOR_STATUS.getCode());
			map.put("err_msg", ResponseCode.VISITOR_STATUS.getDesc());
			return map;
		}

        if (rel.getMessageString().equals("video")) {
            rel.setLastViewTime(new Timestamp(System.currentTimeMillis()));
        } else {
            rel.setLastViewTimeAudio(new Timestamp(System.currentTimeMillis()));
        }

        UserVideoRel userVideoRel = userVideoRelDao.queryInfoByUserIdAndVideoId(rel);
        if(userVideoRel != null){
        	SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
            int newMinutes = 0;
            try {
                if (StringUtils.isNotBlank(rel.getLastViewDuration())) {
                    Date oldVideoDate = dateFormat.parse(userVideoRel.getLastViewDuration());
                    Date newDate = dateFormat.parse(rel.getLastViewDuration());
                    newMinutes = oldVideoDate.getMinutes() + newDate.getMinutes();

                } else {
                	if(StringUtils.isNotBlank(userVideoRel.getLastViewDurationAudio())){
                		Date oldVideoDate = dateFormat.parse(userVideoRel.getLastViewDurationAudio());
                        Date newDate = dateFormat.parse(rel.getLastViewDurationAudio());
                        newMinutes = oldVideoDate.getMinutes() + newDate.getMinutes();
                	}else{
                		newMinutes = dateFormat.parse(rel.getLastViewDurationAudio()).getMinutes() ;
                	}
                    
                }
                rel.setAccumulativeDaily(newMinutes);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

		rel.setLastViewTime(new Timestamp(System.currentTimeMillis()));
		int row = userVideoRelDao.updateByUserIdAndVideoId(rel);
		if (row>0) {
			map.put("err_code", 0);
			map.put("err_msg", "修改成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "修改失败");
		}
		return map;
	}

	@Override
	public Object queryVideoViewHistoryByUserId(UserVideoRel rel) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(rel.getUserId() == null ){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		List<VideoViewDTO> list = userVideoRelDao.queryVideoViewHistoryByUserId(rel);
        for (VideoViewDTO videoViewDTO : list) {
            //视频
            if (videoViewDTO.getVideoId() != null) {
                if (videoViewDTO.getFreeFlag() == 0) {
                    Boolean videoVip = RedisUtil.isVideoVip(rel.getUserId(), videoViewDTO.getVideoId());
                    if (videoVip) {
                        videoViewDTO.setIsVipStatus(1);
                    } else {
                        videoViewDTO.setIsVipStatus(0);
                    }
                } else {
                    videoViewDTO.setIsVipStatus(0);
                }

                PolyInfo polyInfo = RedisUtil.cache(videoViewDTO.getVideoId() + "");
                videoViewDTO.setPolyInfo(polyInfo);
            }
        }
        if (null != list && list.size() > 0) {
            map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("list", list);
		}else {
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
			map.put("list", null);
		}
		return map;
	}

	@Override
	public Object queryStudentsRanking(UserVideoRel rel) {
		Map<String,Object> map = new HashMap<String , Object>();
		//排名榜
		List<StundentRankingDTO> list = userVideoRelDao.queryStudentsRankingByUserId(rel);
		if(null != list && list.size() > 0){
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("ranking_list", list);
		}else{
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
			map.put("ranking_list", null);
		}
		return map;
	}

	@Override
	public Object queryStudentsRankingByUserId(UserVideoRel rel) {
		Map<String,Object> map = new HashMap<String , Object>();
		if(rel.getUserId() == null ){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		//个人排名信息
		List<StundentRankingDTO> personList = userVideoRelDao.queryStudentsRankingByUserId(rel);
		if(null != personList && personList.size() > 0){
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("person_ranking", personList.get(0));
		}else{
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
			map.put("person_ranking", null);
		}
		return map;
	}

	@Override
	public Object queryFinishedCoursePackListByUserId(UserVideoRel rel) {
		Map<String,Object> map = new HashMap<String , Object>();
		if(rel.getUserId() == null ){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		List<CoursePackageViewDTO> list = userVideoRelDao.queryFinishedCoursePackListByUserId(rel);
		if(null != list && list.size() > 0){
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("course_list", list);
		}else {
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
			map.put("course_list", null);
		}
		return map;
	}

	@Override
	public Object queryFinishedVideoListByUserId(UserVideoRel rel) {
		Map<String,Object> map = new HashMap<String , Object>();
		if(rel.getUserId() == null ){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		List<VideoViewDTO> list = userVideoRelDao.queryFinishedVideoListByUserId(rel);
        for (VideoViewDTO videoViewDTO : list) {
            //视频
            if (videoViewDTO.getVideoId() != null) {
                VideoInfo vInfo = (VideoInfo) videoInfoDao.queryById(videoViewDTO.getVideoId());
                if (vInfo != null) {
                    videoViewDTO.setFreeFlag(vInfo.getFreeFlag());
                    videoViewDTO.setOriginalPrice(vInfo.getOriginalPrice());
                }

                if (vInfo.getFreeFlag() == 0) {
                    Boolean videoVip = RedisUtil.isVideoVip(rel.getId(), videoViewDTO.getVideoId());
                    if (videoVip) {
                        videoViewDTO.setIsVipStatus(1);
                    } else {
                        videoViewDTO.setIsVipStatus(0);
                    }
                } else {
                    videoViewDTO.setIsVipStatus(0);
                }

                PolyInfo polyInfo = RedisUtil.cache(vInfo.getId() + "");
                videoViewDTO.setPolyInfo(polyInfo);
            }
        }

		if(null != list && list.size() > 0){
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("video_list", list);
		}else {
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
			map.put("video_list", null);
		}
		return map;
	}

	@Override
	public Object queryKeepDayRankingListByUserId(UserVideoRel rel) {
		Map<String,Object> map = new HashMap<String , Object>();
		if(rel.getUserId() == null ){
			map.put("err_code", -1);
			map.put("err_msg", "用户id为空");
			return map;
		}
		List<SignInKeepDayDTO> list = userVideoRelDao.queryKeepDayRankingListByUserId(rel);
        if (null != list && list.size() > 0) {
            SignInKeepDayDTO signInKeepDayDTO = list.get(0);
            if (signInKeepDayDTO.getContiDay() > 0) {
                IntegralInfo info = new IntegralInfo();
                info.setUserId(rel.getUserId());
                info.setTypeId("7");
                info.setRows(1);
                List<IntegralInfo> integralInfos = integralInfoDao.queryListByInfo(info);
                IntegralInfo integralInfo = integralInfos.get(0);
                Integer score = integralInfo.getScore();
                map.put("score", score);
            } else {
                map.put("score", 0);
            }

            map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("person_ranking", list.get(0));
		}else {
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
            SignInKeepDayDTO signInKeepDayDTO = new SignInKeepDayDTO();
            signInKeepDayDTO.setContiDay(0);
            signInKeepDayDTO.setAccumulateDay(0);
            signInKeepDayDTO.setRowNum(20000);
            map.put("person_ranking", signInKeepDayDTO);
        }
		return map;
	}

	@Override
	public Object queryKeepDayRankingList(UserVideoRel rel) {
		Map<String,Object> map = new HashMap<String , Object>();
		List<SignInKeepDayDTO> list = userVideoRelDao.queryKeepDayRankingListByUserId(rel);
		if(null != list && list.size() > 0){
			map.put("err_code", 200);
			map.put("err_msg", "查询成功");
			map.put("ranking_list", list);
		}else {
			map.put("err_code", 201);
			map.put("err_msg", "查询无数据");
			map.put("ranking_list", null);
		}
		return map;
	}


    @Override
    public Object queryUserInCourseVideo(CustomModuleCoursePackageDto customModuleCoursePackageDto) {
        Map<String, Object> map = new HashMap<String, Object>();

        List<StundentRankingDTO> list = userVideoRelDao.queryUserInCourseVideo(customModuleCoursePackageDto.getCoursepackageId());

        int learning_num = userVideoRelDao.countUserInCourseVideo(customModuleCoursePackageDto.getCoursepackageId());
        map.put("user_list", list);
        map.put("learning_num", learning_num);
        map.put("err_code", 200);
        map.put("err_msg", "查询成功");
        return map;
    }
}
